import * as THREE from '../../build/three.module.js';
import {
  OrbitControls
} from '../../jsm/controls/OrbitControls.js';
import Stats from '../../jsm/libs/stats.module.js';

const stats = new Stats();
const sts = stats.domElement.style;
sts.position = 'absolute';
sts.top = '0px';
sts.right = '0px';
document.body.appendChild(stats.domElement);
let fps = 0; // 帧数

const scene = new THREE.Scene();

/**
 * 雨滴-精灵
 */
const rainBoxWidth = 1600;
const rainCount = 400;
const rainWidth = 20;
const rainSpeed = 500; // 雨滴运动的速度，单位：像素/秒 ，即500像素每秒
const rainGroup = new THREE.Group();
// 雨滴精灵
const txrRain = new THREE.TextureLoader().load("../../textures/sprite_rain.png");
// 循环构建雨滴精灵
for(let i = 0; i < rainCount; i += 1) {
  const rainSpriteMat = new THREE.SpriteMaterial({
    map: txrRain
  });
  const sprite_rain = new THREE.Sprite(rainSpriteMat);
  sprite_rain.scale.set(rainWidth, rainWidth, 1);
  const kx = Math.random() - .5;
  const ky = Math.random();
  const kz = Math.random() - .5;
  sprite_rain.position.set(rainBoxWidth * kx, rainBoxWidth / 2 * ky, rainBoxWidth * kz);
  rainGroup.add(sprite_rain);
}
scene.add(rainGroup);

/**
 * 草地
 */
const planeGeo = new THREE.PlaneGeometry(2000, 2000);
const txrGrass = new THREE.TextureLoader().load('../../textures/grass.png');
txrGrass.wrapS = THREE.RepeatWrapping;
txrGrass.wrapT = THREE.RepeatWrapping;
txrGrass.repeat.set(20, 20);
const planeMat = new THREE.MeshLambertMaterial({
  map: txrGrass,
  side: THREE.DoubleSide
});
const grass = new THREE.Mesh(planeGeo, planeMat);
grass.rotateX(Math.PI / 2);
scene.add(grass);

const al = new THREE.AmbientLight(0xffffff);
scene.add(al);

// const axesH = new THREE.AxesHelper(1000);
// scene.add(axesH);

const k = innerWidth / innerHeight,
      s = 60,
      camera = new THREE.PerspectiveCamera(s, k, 1, 10000);
camera.position.set(800, 200, 800);
camera.lookAt(scene.position);

const renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0x000000);
renderer.setSize(innerWidth, innerHeight);

document.body.appendChild(renderer.domElement);

new OrbitControls(camera, renderer.domElement);

// 帧动画-更新雨滴位置
const updateRain = () => {
  // 根据当前的 fps 和 预计的下落速度，计算出每帧下落的像素数，即 像素/帧
  const ppf = 500 / fps;
  rainGroup.children.forEach(rain => {
    rain.position.y -= ppf;
    if (rain.position.y < 0) { // 落到地面，后重新下落
      rain.position.y = rainBoxWidth / 2;
    }
  });
}

(function render() {
  fps = stats.update().fps;
  if (fps > 0) {
    updateRain();
  }
  renderer.render(scene, camera);
  requestAnimationFrame(render);
})();